#给D2SE启动游戏.exe打补丁，增加1.13d/1.14a/1.14b/1.14c/1.14d五个版本
import sys, traceback
from patch_api import hack_dll_batch, patch_path, target_path, patch_file
import subprocess
from shutil import copyfile

try:
    filename = "%s\\..\\..\\D2SE启动游戏.exe" % target_path
    '''
    00401000    55              push ebp
    00403D02  - E9 19DA0000     jmp D2SE启动.00411720
    00403D07    89C3            mov ebx,eax
    00411720    6A 08           push 0x8 ; /Flags = LOAD_WITH_ALTERED_SEARCH_PATH
    00411722    6A 00           push 0x0 ; |hFile = NULL
    00411724    68 12174100     push D2SE启动.00411712 ; ASCII "D2SEPatch.dll"
    00411729    FF15 2C924100   call dword ptr ds:[0x41922C] ; kernel32.LoadLibraryExA
    0041172F    E8 6CFAFFFF     call D2SE启动.004111A0
    00411734  - E9 CE25FFFF     jmp D2SE启动.00403D07
    '''
    hack_bin = [0xE9, 0x19, 0xDA]   #0xE8, 0x99, 0xD4
    hack_dll_batch(filename, hack_bin, 0x3102)
    hack_bin = [0x44, 0x32, 0x53, 0x45, 0x50, 0x61, 0x74, 0x63, 0x68, 0x2E, 0x64, 0x6C, 0x6C, 0x00, 0x6A, 0x08, 0x6A, 0x00, 0x68, 0x12, 0x17, 0x41, 0x00, 0xFF, 0x15, 0x2C, 0x92, 0x41, 0x00, 0xE8, 0x6C, 0xFA, 0xFF, 0xFF, 0xE9, 0xCE, 0x25, 0xFF, 0xFF]   #all 0
    hack_dll_batch(filename, hack_bin, 0x10B12)
    copyfile("%s\\D2SE\\D2SEPatch.dll" % patch_path, "%s\\..\\..\\D2SEPatch.dll" % target_path)

    child = subprocess.run("%s\\D2SE\\privil.bat %s" % (patch_path, filename), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)  #设置exe的兼容性和管理员权限

    patch_file(2, "D2SE\\", "..\\..\\D2SE\\CORES\\", "1.13d")
    copyfile("%s\\D2SE\\start.bat" % patch_path, "%s\\..\\..\\start.bat" % target_path) #批处理启动
except:
    print("Unexpected error:", sys.exc_info())
    print(traceback.format_exc())
    exit(1)